package com.lovely602.ai.alibaba.controller.memory;


import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author lizhixing
 */
@Slf4j
@RequestMapping(value = "/memory")
@RestController
public class MemoryController {

    private static final String SYSTEM_MESSAGE = "你是一名旅游规划设计师，可以为顾客提供优质的服务";

    private final ChatClient chatClient;

    public MemoryController(ChatClient.Builder builder) {

        // 内存聊天记忆存储库
        ChatMemoryRepository chatMemoryRepository = new InMemoryChatMemoryRepository();

        // 消息窗口聊天记忆
        MessageWindowChatMemory chatMemory = MessageWindowChatMemory
                .builder()
                .chatMemoryRepository(chatMemoryRepository)
                .maxMessages(50) // 最多记忆50条消息
                .build();

        // 消息聊天记忆顾问
        MessageChatMemoryAdvisor messageChatMemoryAdvisor = MessageChatMemoryAdvisor
                .builder(chatMemory)
                .build();

        this.chatClient = builder.defaultSystem(SYSTEM_MESSAGE)
                .defaultAdvisors(messageChatMemoryAdvisor)
                .build();
    }

    /**
     * 携带记忆聊天
     */
    @GetMapping(value = "/chat")
    public String chat(@RequestParam(value = "msg", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？", required = true) String msg,
                       @RequestParam(value = "chatId", defaultValue = "default", required = true) String chatId) {
        return chatClient.prompt()
                .user(msg)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .call()
                .content();
    }

}
